// 导航守卫逻辑
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

// 进度条
NProgress.configure({ showSpinner: false })
// 白名单
const whiteList = ['/login', '/auth-redirect']

// 路由之前，逻辑判定
router.beforeEach(async(to, from, next) => {

  NProgress.start()// 开始进度条
  
  document.title = getPageTitle(to.meta.title)// set page title

  const hasToken = getToken()// 判断用户是否已经登录

  if (hasToken) {// 已登录
    // 想去登录页，重定向至首页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 想去其他页面，先判断用户是否通过getInfo获取了权限角色
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        // 有则跳过
        next()
      } else {
        try {
          // 请求用户信息
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          // 根据角色生成可访问的路由映射
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // 动态添加可访问路由
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // 清除token，返回登录页
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 未登录，且不在白名单内，返回登录页
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

// 进度条完毕
router.afterEach(() => {
  NProgress.done()
})
